using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using ZSW.Framework.Utils;

namespace ZSW.Framework.EditorTools
{
    public class RandomRotateByName : EditorWindow
    {
        string objectName = "";
        Vector3 rotation = Vector3.zero;

        [MenuItem("Tools/Transform/Random Rotate By Name")]
        public static void Invoke()
        {
            GetWindow<RandomRotateByName>("Random Rotate By Name");
        }

        public void OnGUI()
        {
            objectName = EditorGUILayout.TextField("Object Name", objectName);
            rotation = EditorGUILayout.Vector3Field("Rotation", rotation);

            if (GUILayout.Button("Rotate Objects"))
            {
                RotateObjects();
            }
        }

        public void RotateObjects()
        {
            int count = 0;
            GameObject[] allObjects = FindObjectsOfType<GameObject>();
            foreach (GameObject obj in allObjects)
            {
                if (obj.name == objectName)
                {
                    float randomRotationX = Random.Range(-rotation.x, rotation.x);
                    float randomRotationY = Random.Range(-rotation.y, rotation.y);
                    float randomRotationZ = Random.Range(-rotation.z, rotation.z);

                    Vector3 newRotation = obj.transform.eulerAngles + new Vector3(randomRotationX, randomRotationY, randomRotationZ);

                    newRotation.x = (newRotation.x > 180) ? newRotation.x - 360 : newRotation.x;
                    newRotation.y = (newRotation.y > 180) ? newRotation.y - 360 : newRotation.y;
                    newRotation.z = (newRotation.z > 180) ? newRotation.z - 360 : newRotation.z;

                    Undo.RecordObject(obj.transform, "Random Rotate");
                    obj.transform.eulerAngles = newRotation;
                    count++;
                }
            }
            ZSWFUtil_Debug.Log($"随机旋转执行完毕，总计:{count}");
        }
    }
}